home *** CD-ROM | disk | FTP | other *** search
/ Games of Daze / Infomagic - Games of Daze (Summer 1995) (Disc 1 of 2).iso / djgpp / src / patch-2.1 / patch.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-20  |  23.3 KB  |  950 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.2.0 90/05/01 22:17:50 davison Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  13.  * patch12u: unidiff support added
  14.  * 
  15.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  16.  * patch12: rindex() wasn't declared
  17.  * 
  18.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  19.  * patch10: exit code improved.
  20.  * patch10: better support for non-flexfilenames.
  21.  * 
  22.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  23.  * Short replacement caused spurious "Out of sync" message.
  24.  * 
  25.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  26.  * Improved diagnostic on sync error.
  27.  * Moved do_ed_script() to pch.c.
  28.  * 
  29.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  30.  * Fuzz factor caused offset of installed lines.
  31.  * 
  32.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  33.  * Backwards search could terminate prematurely.
  34.  * 
  35.  * Revision 2.0  86/09/17  15:37:32  lwall
  36.  * Baseline for netwide release.
  37.  * 
  38.  * Revision 1.5  86/08/01  20:53:24  lwall
  39.  * Changed some %d's to %ld's.
  40.  * Linted.
  41.  * 
  42.  * Revision 1.4  86/08/01  19:17:29  lwall
  43.  * Fixes for machines that can't vararg.
  44.  * Added fuzz factor.
  45.  * Generalized -p.
  46.  * General cleanup.
  47.  * 
  48.  * 85/08/15 van%ucbmonet@berkeley
  49.  * Changes for 4.3bsd diff -c.
  50.  *
  51.  * Revision 1.3  85/03/26  15:07:43  lwall
  52.  * Frozen.
  53.  * 
  54.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  55.  * Changed pfp->_file to fileno(pfp).
  56.  * 
  57.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  58.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  59.  * Also allow ed output to be suppressed.
  60.  * 
  61.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  62.  * Added -p option from jromine@uci-750a.
  63.  * 
  64.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  65.  * Now checks for normalness of file to patch.
  66.  * 
  67.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  68.  * Added -D (#ifdef) option from joe@fluke.
  69.  * 
  70.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  71.  * Made smarter about SCCS subdirectories.
  72.  * 
  73.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  74.  * Added -l switch to do loose string comparison.
  75.  * 
  76.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  77.  * Failed hunk count not reset on multiple patch file.
  78.  * 
  79.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  80.  * Branch for sdcrdcf changes.
  81.  * 
  82.  * Revision 1.2  84/11/29  13:29:51  lwall
  83.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  84.  * multiple calls to mktemp().  Will now work on machines that can only
  85.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  86.  * Various cosmetic changes.
  87.  * 
  88.  * Revision 1.1  84/11/09  17:03:58  lwall
  89.  * Initial revision
  90.  * 
  91.  */
  92.  
  93. #include "INTERN.h"
  94. #include "common.h"
  95. #include "EXTERN.h"
  96. #include "version.h"
  97. #include "util.h"
  98. #include "pch.h"
  99. #include "inp.h"
  100. #include "backupfile.h"
  101. #include "getopt.h"
  102.  
  103. /* procedures */
  104.  
  105. void reinitialize_almost_everything();
  106. void get_some_switches();
  107. LINENUM locate_hunk();
  108. void abort_hunk();
  109. void apply_hunk();
  110. void init_output();
  111. void init_reject();
  112. void copy_till();
  113. void spew_output();
  114. void dump_line();
  115. bool patch_match();
  116. bool similar();
  117. void re_input();
  118. void my_exit();
  119.  
  120. /* TRUE if -E was specified on command line.  */
  121. static int remove_empty_files = FALSE;
  122.  
  123. /* TRUE if -R was specified on command line.  */
  124. static int reverse_flag_specified = FALSE;
  125.  
  126. /* Apply a set of diffs as appropriate. */
  127.  
  128. int
  129. main(argc,argv)
  130. int argc;
  131. char **argv;
  132. {
  133.     LINENUM where;
  134.     LINENUM newwhere;
  135.     LINENUM fuzz;
  136.     LINENUM mymaxfuzz;
  137.     int hunk = 0;
  138.     int failed = 0;
  139.     int failtotal = 0;
  140.     bool rev_okayed = 0;
  141.     int i;
  142.  
  143.     setbuf(stderr, serrbuf);
  144.     for (i = 0; i<MAXFILEC; i++)
  145.     filearg[i] = Nullch;
  146.  
  147.     myuid = getuid();
  148.  
  149.     /* Cons up the names of the temporary files.  */
  150.     {
  151.       /* Directory for temporary files.  */
  152.       char *tmpdir;
  153.       int tmpname_len;
  154.  
  155.       tmpdir = getenv ("TMPDIR");
  156.       if (tmpdir == NULL) {
  157.     tmpdir = "/tmp";
  158.       }
  159.       tmpname_len = strlen (tmpdir) + 20;
  160.  
  161.       TMPOUTNAME = (char *) malloc (tmpname_len);
  162.       strcpy (TMPOUTNAME, tmpdir);
  163.       strcat (TMPOUTNAME, "/patchoXXXXXX");
  164.       Mktemp(TMPOUTNAME);
  165.  
  166.       TMPINNAME = (char *) malloc (tmpname_len);
  167.       strcpy (TMPINNAME, tmpdir);
  168.       strcat (TMPINNAME, "/patchiXXXXXX");
  169.       Mktemp(TMPINNAME);
  170.  
  171.       TMPREJNAME = (char *) malloc (tmpname_len);
  172.       strcpy (TMPREJNAME, tmpdir);
  173.       strcat (TMPREJNAME, "/patchrXXXXXX");
  174.       Mktemp(TMPREJNAME);
  175.  
  176.       TMPPATNAME = (char *) malloc (tmpname_len);
  177.       strcpy (TMPPATNAME, tmpdir);
  178.       strcat (TMPPATNAME, "/patchpXXXXXX");
  179.       Mktemp(TMPPATNAME);
  180.     }
  181.  
  182.     {
  183.       char *v;
  184.  
  185.       v = getenv ("SIMPLE_BACKUP_SUFFIX");
  186.       if (v)
  187.     simple_backup_suffix = v;
  188.       else
  189. #ifdef __MSDOS__
  190.     simple_backup_suffix = "~"; /* 8.3 filesystem leaves few options */
  191. #else
  192.     simple_backup_suffix = ".orig";
  193. #endif
  194. #ifndef NODIR
  195.       v = getenv ("VERSION_CONTROL");
  196.       backup_type = get_version (v); /* OK to pass NULL. */
  197. #endif
  198.     }
  199.  
  200.     /* parse switches */
  201.     Argc = argc;
  202.     Argv = argv;
  203.     get_some_switches();
  204.     
  205.     /* make sure we clean up /tmp in case of disaster */
  206.     set_signals(0);
  207.  
  208.     for (
  209.     open_patch_file(filearg[1]);
  210.     there_is_another_patch();
  211.     reinitialize_almost_everything()
  212.     ) {                    /* for each patch in patch file */
  213.  
  214.     if (outname == Nullch)
  215.         outname = savestr(filearg[0]);
  216.     
  217.     /* for ed script just up and do it and exit */
  218.     if (diff_type == ED_DIFF) {
  219.         do_ed_script();
  220.         continue;
  221.     }
  222.     
  223.     /* initialize the patched file */
  224.     if (!skip_rest_of_patch)
  225.         init_output(TMPOUTNAME);
  226.     
  227.     /* initialize reject file */
  228.     init_reject(TMPREJNAME);
  229.     
  230.     /* find out where all the lines are */
  231.     if (!skip_rest_of_patch)
  232.         scan_input(filearg[0]);
  233.     
  234.     /* from here on, open no standard i/o files, because malloc */
  235.     /* might misfire and we can't catch it easily */
  236.     
  237.     /* apply each hunk of patch */
  238.     hunk = 0;
  239.     failed = 0;
  240.     rev_okayed = FALSE;
  241.     out_of_mem = FALSE;
  242.     while (another_hunk()) {
  243.         hunk++;
  244.         fuzz = Nulline;
  245.         mymaxfuzz = pch_context();
  246.         if (maxfuzz < mymaxfuzz)
  247.         mymaxfuzz = maxfuzz;
  248.         if (!skip_rest_of_patch) {
  249.         do {
  250.             where = locate_hunk(fuzz);
  251.             if (hunk == 1 && where == Nulline && !(force|rev_okayed)) {
  252.                         /* dwim for reversed patch? */
  253.             if (!pch_swap()) {
  254.                 if (fuzz == Nulline)
  255.                 say1(
  256. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  257.                 continue;
  258.             }
  259.             reverse = !reverse;
  260.             where = locate_hunk(fuzz);  /* try again */
  261.             if (where == Nulline) {        /* didn't find it swapped */
  262.                 if (!pch_swap())         /* put it back to normal */
  263.                 fatal1("lost hunk on alloc error!\n");
  264.                 reverse = !reverse;
  265.             }
  266.             else if (noreverse) {
  267.                 if (!pch_swap())         /* put it back to normal */
  268.                 fatal1("lost hunk on alloc error!\n");
  269.                 reverse = !reverse;
  270.                 say1(
  271. "Ignoring previously applied (or reversed) patch.\n");
  272.                 skip_rest_of_patch = TRUE;
  273.             }
  274.             else if (batch) {
  275.                 if (verbose)
  276.                 say3(
  277. "%seversed (or previously applied) patch detected!  %s -R.",
  278.                 reverse ? "R" : "Unr",
  279.                 reverse ? "Assuming" : "Ignoring");
  280.             }
  281.             else {
  282.                 ask3(
  283. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  284.                 reverse ? "R" : "Unr",
  285.                 reverse ? "Assume" : "Ignore");
  286.                 if (*buf == 'n') {
  287.                 ask1("Apply anyway? [n] ");
  288.                 if (*buf == 'y')
  289.                     rev_okayed = TRUE;
  290.                 else
  291.                     skip_rest_of_patch = TRUE;
  292.                 where = Nulline;
  293.                 reverse = !reverse;
  294.                 if (!pch_swap())  /* put it back to normal */
  295.                     fatal1("lost hunk on alloc error!\n");
  296.                 }
  297.             }
  298.             }
  299.         } while (!skip_rest_of_patch && where == Nulline &&
  300.             ++fuzz <= mymaxfuzz);
  301.  
  302.         if (skip_rest_of_patch) {        /* just got decided */
  303.             Fclose(ofp);
  304.             ofp = Nullfp;
  305.         }
  306.         }
  307.  
  308.         newwhere = pch_newfirst() + last_offset;
  309.         if (skip_rest_of_patch) {
  310.         abort_hunk();
  311.         failed++;
  312.         if (verbose)
  313.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  314.         }
  315.         else if (where == Nulline) {
  316.         abort_hunk();
  317.         failed++;
  318.         if (verbose)
  319.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  320.         }
  321.         else {
  322.         apply_hunk(where);
  323.         if (verbose) {
  324.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  325.             if (fuzz)
  326.             say2(" with fuzz %ld", fuzz);
  327.             if (last_offset)
  328.             say3(" (offset %ld line%s)",
  329.                 last_offset, last_offset==1L?"":"s");
  330.             say1(".\n");
  331.         }
  332.         }
  333.     }
  334.  
  335.     if (out_of_mem && using_plan_a) {
  336.         optind = optind_last;
  337.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  338.         if (ofp)
  339.             Fclose(ofp);
  340.         ofp = Nullfp;
  341.         if (rejfp)
  342.             Fclose(rejfp);
  343.         rejfp = Nullfp;
  344.         continue;
  345.     }
  346.     
  347.     assert(hunk);
  348.     
  349.     /* finish spewing out the new file */
  350.     if (!skip_rest_of_patch)
  351.         spew_output();
  352.     
  353.     /* and put the output where desired */
  354.     ignore_signals();
  355.     if (!skip_rest_of_patch) {
  356.         struct stat statbuf;
  357.         char *realout = outname;
  358.  
  359.         if (move_file(TMPOUTNAME, outname) < 0) {
  360.         toutkeep = TRUE;
  361.         realout = TMPOUTNAME;
  362.         chmod(TMPOUTNAME, filemode);
  363.         }
  364.         else
  365.         chmod(outname, filemode);
  366.  
  367.         if (remove_empty_files && stat(realout, &statbuf) == 0
  368.         && statbuf.st_size == 0) {
  369.         if (verbose)
  370.             say2("Removing %s (empty after patching).\n", realout);
  371.             while (unlink(realout) >= 0) ; /* while is for Eunice.  */
  372.         }
  373.     }
  374.     Fclose(rejfp);
  375.     rejfp = Nullfp;
  376.     if (failed) {
  377.         failtotal += failed;
  378.         if (!*rejname) {
  379.         Strcpy(rejname, outname);
  380.         addext(rejname, ".rej", '#');
  381.         }
  382.         if (skip_rest_of_patch) {
  383.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  384.             failed, hunk, rejname);
  385.         }
  386.         else {
  387.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  388.             failed, hunk, rejname);
  389.         }
  390.         if (move_file(TMPREJNAME, rejname) < 0)
  391.         trejkeep = TRUE;
  392.     }
  393.     set_signals(1);
  394.     }
  395.     my_exit(failtotal);
  396. }
  397.  
  398. /* Prepare to find the next patch to do in the patch file. */
  399.  
  400. void
  401. reinitialize_almost_everything()
  402. {
  403.     re_patch();
  404.     re_input();
  405.  
  406.     input_lines = 0;
  407.     last_frozen_line = 0;
  408.  
  409.     filec = 0;
  410.     if (filearg[0] != Nullch && !out_of_mem) {
  411.     free(filearg[0]);
  412.     filearg[0] = Nullch;
  413.     }
  414.  
  415.     if (outname != Nullch) {
  416.     free(outname);
  417.     outname = Nullch;
  418.     }
  419.  
  420.     last_offset = 0;
  421.  
  422.     diff_type = 0;
  423.  
  424.     if (revision != Nullch) {
  425.     free(revision);
  426.     revision = Nullch;
  427.     }
  428.  
  429.     reverse = reverse_flag_specified;
  430.     skip_rest_of_patch = FALSE;
  431.  
  432.     get_some_switches();
  433.  
  434.     if (filec >= 2)
  435.     fatal1("you may not change to a different patch file\n");
  436. }
  437.  
  438. static char *shortopts = "-b:B:cd:D:eEfF:lnNo:p::r:RsStuvV:x:";
  439. static struct option longopts[] =
  440. {
  441.   {"suffix", 1, NULL, 'b'},
  442.   {"prefix", 1, NULL, 'B'},
  443.   {"context", 0, NULL, 'c'},
  444.   {"directory", 1, NULL, 'd'},
  445.   {"ifdef", 1, NULL, 'D'},
  446.   {"ed", 0, NULL, 'e'},
  447.   {"remove-empty-files", 0, NULL, 'E'},
  448.   {"force", 0, NULL, 'f'},
  449.   {"fuzz", 1, NULL, 'F'},
  450.   {"ignore-whitespace", 0, NULL, 'l'},
  451.   {"normal", 0, NULL, 'n'},
  452.   {"forward", 0, NULL, 'N'},
  453.   {"output", 1, NULL, 'o'},
  454.   {"strip", 2, NULL, 'p'},
  455.   {"reject-file", 1, NULL, 'r'},
  456.   {"reverse", 0, NULL, 'R'},
  457.   {"quiet", 0, NULL, 's'},
  458.   {"silent", 0, NULL, 's'},
  459.   {"skip", 0, NULL, 'S'},
  460.   {"batch", 0, NULL, 't'},
  461.   {"unified", 0, NULL, 'u'},
  462.   {"version", 0, NULL, 'v'},
  463.   {"version-control", 1, NULL, 'V'},
  464.   {"debug", 1, NULL, 'x'},
  465.   {0, 0, 0, 0}
  466. };
  467.  
  468. /* Process switches and filenames up to next '+' or end of list. */
  469.  
  470. void
  471. get_some_switches()
  472. {
  473.     Reg1 int optc;
  474.  
  475.     rejname[0] = '\0';
  476.     optind_last = optind;
  477.     if (optind == Argc)
  478.     return;
  479.     while ((optc = getopt_long (Argc, Argv, shortopts, longopts, (int *) 0))
  480.        != -1) {
  481.     if (optc == 1) {
  482.         if (strEQ(optarg, "+"))
  483.         return;
  484.         if (filec == MAXFILEC)
  485.         fatal1("too many file arguments\n");
  486.         filearg[filec++] = savestr(optarg);
  487.     }
  488.     else {
  489.         switch (optc) {
  490.         case 'b':
  491.         simple_backup_suffix = savestr(optarg);
  492.         break;
  493.         case 'B':
  494.         origprae = savestr(optarg);
  495.         break;
  496.         case 'c':
  497.         diff_type = CONTEXT_DIFF;
  498.         break;
  499.         case 'd':
  500.         if (chdir(optarg) < 0)
  501.             pfatal2("can't cd to %s", optarg);
  502.         break;
  503.         case 'D':
  504.             do_defines = TRUE;
  505.         if (!isalpha(*optarg) && '_' != *optarg)
  506.             fatal1("argument to -D is not an identifier\n");
  507.         Sprintf(if_defined, "#ifdef %s\n", optarg);
  508.         Sprintf(not_defined, "#ifndef %s\n", optarg);
  509.         Sprintf(end_defined, "#endif /* %s */\n", optarg);
  510.         break;
  511.         case 'e':
  512.         diff_type = ED_DIFF;
  513.         break;
  514.         case 'E':
  515.         remove_empty_files = TRUE;
  516.         break;
  517.         case 'f':
  518.         force = TRUE;
  519.         break;
  520.         case 'F':
  521.         maxfuzz = atoi(optarg);
  522.         break;
  523.         case 'l':
  524.         canonicalize = TRUE;
  525.         break;
  526.         case 'n':
  527.         diff_type = NORMAL_DIFF;
  528.         break;
  529.         case 'N':
  530.         noreverse = TRUE;
  531.         break;
  532.         case 'o':
  533.         outname = savestr(optarg);
  534.         break;
  535.         case 'p':
  536.         if (optarg)
  537.             strippath = atoi(optarg);
  538.         else
  539.             strippath = 0;
  540.         break;
  541.         case 'r':
  542.         Strcpy(rejname, optarg);
  543.         break;
  544.         case 'R':
  545.         reverse = TRUE;
  546.         reverse_flag_specified = TRUE;
  547.         break;
  548.         case 's':
  549.         verbose = FALSE;
  550.         break;
  551.         case 'S':
  552.         skip_rest_of_patch = TRUE;
  553.         break;
  554.         case 't':
  555.         batch = TRUE;
  556.         break;
  557.         case 'u':
  558.         diff_type = UNI_DIFF;
  559.         break;
  560.         case 'v':
  561.         version();
  562.         break;
  563.         case 'V':
  564. #ifndef NODIR
  565.         backup_type = get_version (optarg);
  566. #endif
  567.         break;
  568. #ifdef DEBUGGING
  569.         case 'x':
  570.         debug = atoi(optarg);
  571.         break;
  572. #endif
  573.         default:
  574.         fprintf(stderr, "\
  575. Usage: %s [options] [origfile [patchfile]] [+ [options] [origfile]]...\n",
  576.             Argv[0]);
  577.         fprintf(stderr, "\
  578. Options:\n\
  579.        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  580.        [-D symbol] [-F max-fuzz] [-o out-file] [-p[strip-count]]\n\
  581.        [-r rej-name] [-V {numbered,existing,simple}] [--context]\n\
  582.        [--prefix=backup-prefix] [--suffix=backup-ext] [--ifdef=symbol]\n\
  583.        [--directory=directory] [--ed] [--fuzz=max-fuzz] [--force] [--batch]\n\
  584.        [--ignore-whitespace] [--forward] [--reverse] [--output=out-file]\n");
  585.         fprintf(stderr, "\
  586.        [--strip[=strip-count]] [--normal] [--reject-file=rej-name] [--skip]\n\
  587.        [--remove-empty-files] [--quiet] [--silent] [--unified] [--version]\n\
  588.        [--version-control={numbered,existing,simple}]\n");
  589.         my_exit(1);
  590.         }
  591.     }
  592.     }
  593.  
  594.     /* Process any filename args given after "--".  */
  595.     for (; optind < Argc; ++optind) {
  596.     if (filec == MAXFILEC)
  597.         fatal1("too many file arguments\n");
  598.     filearg[filec++] = savestr(Argv[optind]);
  599.     }
  600. }
  601.  
  602. /* Attempt to find the right place to apply this hunk of patch. */
  603.  
  604. LINENUM
  605. locate_hunk(fuzz)
  606. LINENUM fuzz;
  607. {
  608.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  609.     Reg2 LINENUM offset;
  610.     LINENUM pat_lines = pch_ptrn_lines();
  611.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  612.                 - pat_lines + 1; 
  613.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  614.                 + pch_context();
  615.  
  616.     if (!pat_lines)            /* null range matches always */
  617.     return first_guess;
  618.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  619.     max_neg_offset = first_guess - 1;
  620.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  621.     return first_guess;
  622.     for (offset = 1; ; offset++) {
  623.     Reg5 bool check_after = (offset <= max_pos_offset);
  624.     Reg6 bool check_before = (offset <= max_neg_offset);
  625.  
  626.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  627. #ifdef DEBUGGING
  628.         if (debug & 1)
  629.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  630. #endif
  631.         last_offset = offset;
  632.         return first_guess+offset;
  633.     }
  634.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  635. #ifdef DEBUGGING
  636.         if (debug & 1)
  637.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  638. #endif
  639.         last_offset = -offset;
  640.         return first_guess-offset;
  641.     }
  642.     else if (!check_before && !check_after)
  643.         return Nulline;
  644.     }
  645. }
  646.  
  647. /* We did not find the pattern, dump out the hunk so they can handle it. */
  648.  
  649. void
  650. abort_hunk()
  651. {
  652.     Reg1 LINENUM i;
  653.     Reg2 LINENUM pat_end = pch_end();
  654.     /* add in last_offset to guess the same as the previous successful hunk */
  655.     LINENUM oldfirst = pch_first() + last_offset;
  656.     LINENUM newfirst = pch_newfirst() + last_offset;
  657.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  658.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  659.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  660.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  661.  
  662.     fprintf(rejfp, "***************\n");
  663.     for (i=0; i<=pat_end; i++) {
  664.     switch (pch_char(i)) {
  665.     case '*':
  666.         if (oldlast < oldfirst)
  667.         fprintf(rejfp, "*** 0%s\n", stars);
  668.         else if (oldlast == oldfirst)
  669.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  670.         else
  671.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  672.         break;
  673.     case '=':
  674.         if (newlast < newfirst)
  675.         fprintf(rejfp, "--- 0%s\n", minuses);
  676.         else if (newlast == newfirst)
  677.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  678.         else
  679.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  680.         break;
  681.     case '\n':
  682.         fprintf(rejfp, "%s", pfetch(i));
  683.         break;
  684.     case ' ': case '-': case '+': case '!':
  685.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  686.         break;
  687.     default:
  688.         fatal1("fatal internal error in abort_hunk\n"); 
  689.     }
  690.     }
  691. }
  692.  
  693. /* We found where to apply it (we hope), so do it. */
  694.  
  695. void
  696. apply_hunk(where)
  697. LINENUM where;
  698. {
  699.     Reg1 LINENUM old = 1;
  700.     Reg2 LINENUM lastline = pch_ptrn_lines();
  701.     Reg3 LINENUM new = lastline+1;
  702. #define OUTSIDE 0
  703. #define IN_IFNDEF 1
  704. #define IN_IFDEF 2
  705. #define IN_ELSE 3
  706.     Reg4 int def_state = OUTSIDE;
  707.     Reg5 bool R_do_defines = do_defines;
  708.     Reg6 LINENUM pat_end = pch_end();
  709.  
  710.     where--;
  711.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  712.     new++;
  713.     
  714.     while (old <= lastline) {
  715.     if (pch_char(old) == '-') {
  716.         copy_till(where + old - 1);
  717.         if (R_do_defines) {
  718.         if (def_state == OUTSIDE) {
  719.             fputs(not_defined, ofp);
  720.             def_state = IN_IFNDEF;
  721.         }
  722.         else if (def_state == IN_IFDEF) {
  723.             fputs(else_defined, ofp);
  724.             def_state = IN_ELSE;
  725.         }
  726.         fputs(pfetch(old), ofp);
  727.         }
  728.         last_frozen_line++;
  729.         old++;
  730.     }
  731.     else if (new > pat_end) {
  732.         break;
  733.     }
  734.     else if (pch_char(new) == '+') {
  735.         copy_till(where + old - 1);
  736.         if (R_do_defines) {
  737.         if (def_state == IN_IFNDEF) {
  738.             fputs(else_defined, ofp);
  739.             def_state = IN_ELSE;
  740.         }
  741.         else if (def_state == OUTSIDE) {
  742.             fputs(if_defined, ofp);
  743.             def_state = IN_IFDEF;
  744.         }
  745.         }
  746.         fputs(pfetch(new), ofp);
  747.         new++;
  748.     }
  749.     else if (pch_char(new) != pch_char(old)) {
  750.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  751.         pch_hunk_beg() + old,
  752.         pch_hunk_beg() + new);
  753. #ifdef DEBUGGING
  754.         say3("oldchar = '%c', newchar = '%c'\n",
  755.         pch_char(old), pch_char(new));
  756. #endif
  757.         my_exit(1);
  758.     }
  759.     else if (pch_char(new) == '!') {
  760.         copy_till(where + old - 1);
  761.         if (R_do_defines) {
  762.            fputs(not_defined, ofp);
  763.            def_state = IN_IFNDEF;
  764.         }
  765.         while (pch_char(old) == '!') {
  766.         if (R_do_defines) {
  767.             fputs(pfetch(old), ofp);
  768.         }
  769.         last_frozen_line++;
  770.         old++;
  771.         }
  772.         if (R_do_defines) {
  773.         fputs(else_defined, ofp);
  774.         def_state = IN_ELSE;
  775.         }
  776.         while (pch_char(new) == '!') {
  777.         fputs(pfetch(new), ofp);
  778.         new++;
  779.         }
  780.     }
  781.     else {
  782.         assert(pch_char(new) == ' ');
  783.         old++;
  784.         new++;
  785.         if (R_do_defines && def_state != OUTSIDE) {
  786.         fputs(end_defined, ofp);
  787.         def_state = OUTSIDE;
  788.         }
  789.     }
  790.     }
  791.     if (new <= pat_end && pch_char(new) == '+') {
  792.     copy_till(where + old - 1);
  793.     if (R_do_defines) {
  794.         if (def_state == OUTSIDE) {
  795.             fputs(if_defined, ofp);
  796.         def_state = IN_IFDEF;
  797.         }
  798.         else if (def_state == IN_IFNDEF) {
  799.         fputs(else_defined, ofp);
  800.         def_state = IN_ELSE;
  801.         }
  802.     }
  803.     while (new <= pat_end && pch_char(new) == '+') {
  804.         fputs(pfetch(new), ofp);
  805.         new++;
  806.     }
  807.     }
  808.     if (R_do_defines && def_state != OUTSIDE) {
  809.     fputs(end_defined, ofp);
  810.     }
  811. }
  812.  
  813. /* Open the new file. */
  814.  
  815. void
  816. init_output(name)
  817. char *name;
  818. {
  819.     ofp = fopen(name, "w");
  820.     if (ofp == Nullfp)
  821.     pfatal2("can't create %s", name);
  822. }
  823.  
  824. /* Open a file to put hunks we can't locate. */
  825.  
  826. void
  827. init_reject(name)
  828. char *name;
  829. {
  830.     rejfp = fopen(name, "w");
  831.     if (rejfp == Nullfp)
  832.     pfatal2("can't create %s", name);
  833. }
  834.  
  835. /* Copy input file to output, up to wherever hunk is to be applied. */
  836.  
  837. void
  838. copy_till(lastline)
  839. Reg1 LINENUM lastline;
  840. {
  841.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  842.  
  843.     if (R_last_frozen_line > lastline)
  844.     fatal1("misordered hunks! output would be garbled\n");
  845.     while (R_last_frozen_line < lastline) {
  846.     dump_line(++R_last_frozen_line);
  847.     }
  848.     last_frozen_line = R_last_frozen_line;
  849. }
  850.  
  851. /* Finish copying the input file to the output file. */
  852.  
  853. void
  854. spew_output()
  855. {
  856. #ifdef DEBUGGING
  857.     if (debug & 256)
  858.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  859. #endif
  860.     if (input_lines)
  861.     copy_till(input_lines);        /* dump remainder of file */
  862.     Fclose(ofp);
  863.     ofp = Nullfp;
  864. }
  865.  
  866. /* Copy one line from input to output. */
  867.  
  868. void
  869. dump_line(line)
  870. LINENUM line;
  871. {
  872.     Reg1 char *s;
  873.     Reg2 char R_newline = '\n';
  874.  
  875.     /* Note: string is not null terminated. */
  876.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  877. }
  878.  
  879. /* Does the patch pattern match at line base+offset? */
  880.  
  881. bool
  882. patch_match(base, offset, fuzz)
  883. LINENUM base;
  884. LINENUM offset;
  885. LINENUM fuzz;
  886. {
  887.     Reg1 LINENUM pline = 1 + fuzz;
  888.     Reg2 LINENUM iline;
  889.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  890.  
  891.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  892.     if (canonicalize) {
  893.         if (!similar(ifetch(iline, (offset >= 0)),
  894.              pfetch(pline),
  895.              pch_line_len(pline) ))
  896.         return FALSE;
  897.     }
  898.     else if (strnNE(ifetch(iline, (offset >= 0)),
  899.            pfetch(pline),
  900.            pch_line_len(pline) ))
  901.         return FALSE;
  902.     }
  903.     return TRUE;
  904. }
  905.  
  906. /* Do two lines match with canonicalized white space? */
  907.  
  908. bool
  909. similar(a,b,len)
  910. Reg1 char *a;
  911. Reg2 char *b;
  912. Reg3 int len;
  913. {
  914.     while (len) {
  915.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  916.         if (!isspace(*a))        /* no corresponding whitespace? */
  917.         return FALSE;
  918.         while (len && isspace(*b) && *b != '\n')
  919.         b++,len--;        /* skip pattern whitespace */
  920.         while (isspace(*a) && *a != '\n')
  921.         a++;            /* skip target whitespace */
  922.         if (*a == '\n' || *b == '\n')
  923.         return (*a == *b);    /* should end in sync */
  924.     }
  925.     else if (*a++ != *b++)        /* match non-whitespace chars */
  926.         return FALSE;
  927.     else
  928.         len--;            /* probably not necessary */
  929.     }
  930.     return TRUE;            /* actually, this is not reached */
  931.                     /* since there is always a \n */
  932. }
  933.  
  934. /* Exit with cleanup. */
  935.  
  936. void
  937. my_exit(status)
  938. int status;
  939. {
  940.     Unlink(TMPINNAME);
  941.     if (!toutkeep) {
  942.     Unlink(TMPOUTNAME);
  943.     }
  944.     if (!trejkeep) {
  945.     Unlink(TMPREJNAME);
  946.     }
  947.     Unlink(TMPPATNAME);
  948.     exit(status);
  949. }
  950.